package com.inspectortime.webapp.inspector;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.inspectortime.domain.Inspection;
import com.inspectortime.domain.InspectorCompany;
import com.inspectortime.domain.util.InspectionDateComparator;
import com.inspectortime.repository.Repository;
import com.inspectortime.webapp.util.HttpSessionUtils;
import com.inspectortime.webapp.util.InspectionListNameDateComparator;

/**
 * Prepares data for the "Past Inspections" page
 * 
 * @author bones
 *
 */
public class PastInspectionsController implements Controller {

	private Repository repository;
	private String returnView;
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		InspectorCompany company = HttpSessionUtils.retrieveLoggedInCompany(request, repository);
		List<Inspection> pastInspections = company.findInspectionsBetween(null, new Date());
		
		if (StringUtils.hasText(request.getParameter("sort")) && request.getParameter("sort").equals("inspector")) {
			InspectionListNameDateComparator comparator = new InspectionListNameDateComparator();
			Collections.sort(pastInspections, comparator);
		} else {
				
			InspectionDateComparator comparator = new InspectionDateComparator();
			Collections.sort(pastInspections, comparator);
		}
		
		ModelAndView mv = new ModelAndView(this.returnView);
		mv.addObject("inspectorCompany", company);
		mv.addObject("pastInspections", pastInspections);
		return mv;
	}
	
	public void setReturnView(String returnView) {
		this.returnView = returnView;
	}

	public void setRepository(Repository repository) {
		this.repository = repository;
	}


}
